package com.itheima.controller;

import com.itheima.jopo.Classes;
import com.itheima.jopo.PageBean;
import com.itheima.jopo.Result;
import com.itheima.service.ClassesService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

/**
 * ClassesController
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/5/1 10:43
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/classes")
public class ClassesController {

    private final ClassesService classesService;

    @PostMapping
    public Result create(@RequestBody Classes classes) {
        boolean existByName = classesService.existByName(classes.getName());
        if (existByName) {
            return Result.error("班级已经存在");
        }
        classesService.save(classes);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        classesService.removeById(id);
        return Result.success();
    }

    @PutMapping
    public Result modify(@RequestBody Classes classes) {
        boolean existByName = classesService.existByName(classes.getName());
        if (existByName) {
            return Result.error("班级已经存在");
        }
        classesService.updateById(classes);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result queryById(@PathVariable Integer id) {
        Classes classes = classesService.getById(id);
        return Result.success(classes);
    }

    @GetMapping
    public Result page(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                       String name,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        PageBean pageBean = classesService.selectPage(page, pageSize, name, begin, end);
        return Result.success(pageBean);
    }
}
